﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineVideos.Common;
using System.Threading;
using Common.Library;
using Microsoft.Phone.BackgroundAudio;
using OnlineVideos.Views;
using OnlineVideos.View_Models;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using OnlineVideos.UI;
//using OnlineVideos.ViewModels;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;
using OnlineVideos.Entities;
using OnlineVideos.Data;
using OnlineVideos.Utilities;
using Common.Utilities;
using System.Threading.Tasks;
using FlurryWP8SDK.Models;
namespace OnlineVideos
{
    public partial class ShowAudio : UserControl
    {
        #region GlobalDeclaration

        List<ShowLinks> objAudioList;
        PersonGalleryPopup galleryPopup=null;
        private bool IsDataLoaded;
        ShowDetail detailModel;
        bool ringtoneimageclicked = false;

        #endregion

        #region Constructor
        public ShowAudio()
         {
             InitializeComponent();
             objAudioList = new List<ShowLinks>();
             IsDataLoaded = false;

         }
        #endregion

        #region PageLoad
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
            if (IsDataLoaded == false)
            {
                GetPageDataInBackground();
                detailModel = new ShowDetail();
                IsDataLoaded = true;
               
            }
            ringtoneimageclicked = false;
            }
            catch (Exception ex)
            {
           
             Exceptions.SaveOrSendExceptions("Exception in UserControl_Loaded event In ShowAudio.cs file.", ex);
        }
           
        }
        #endregion

        #region "Common Methods"
        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetShowLinksByTypeForWp8(AppSettings.ShowID, LinkType.Audio/*, false*/);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {

                                            objAudioList = (List<ShowLinks>)a.Result;
                                            if (objAudioList.Count > 0)
                                            {
                                                lbxAudioList.ItemsSource = objAudioList;
                                                tblkFavNoAudio.Visibility = Visibility.Collapsed;
                                                
                                                lbxAudioList.Loaded += new RoutedEventHandler(lbxAudioList_Loaded);
                                            }
                                            else
                                            {
                                                lbxAudioList.ItemsSource = null;
                                                tblkFavNoAudio.Text = "No " + AppResources.ShowFavoriteAudioPivotTitle + " available";
                                                tblkFavNoAudio.Visibility = Visibility.Visible;
                                            }
                                        }
                                      );

            bwHelper.RunBackgroundWorkers();
        }
        
        public void LoadDownLoads(LinkHistory linkinfo)
        {
            try
            {
            string linktype = "";
            AppSettings.ShowLinkTitle = linkinfo.LinkUrl;
                AppSettings.AudioTitle = linkinfo.Title;
            if (linktype == ".jpg" || linktype == ".png")
            {
                galleryPopup.Show(linkinfo.ID.ToString());
            }
            else
            {
                if (linkinfo.Songplay == Constants.PlayImagePath)
                {
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == linkinfo.LinkUrl)
                            {

                                cb.IsIndeterminate = true;
                            }
                        }
                    }
                    if (lbxAudioList.ItemsSource != null)
                    {

                        History objHistory = new History();
                        objHistory.SaveAudioHistory((lbxAudioList.SelectedItem as ShowLinks).ShowID.ToString(), (lbxAudioList.SelectedItem as ShowLinks).Title);
                    }
                    AudioTrack audioTrack = new AudioTrack();
                    audioTrack.BeginEdit();
                    string url = string.Empty;
                    if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        url = ResourceHelper.ProjectName + "/Songs/" + linkinfo.LinkUrl;
                    else
                        url = linkinfo.LinkUrl;
                    audioTrack.Source = new Uri(url,UriKind.RelativeOrAbsolute);
                    audioTrack.Title = linkinfo.Title;
                    audioTrack.EndEdit();
                    BackgroundAudioPlayer.Instance.Track = audioTrack;
                    BackgroundAudioPlayer.Instance.Play();
                    BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                    AppSettings.AudioShowID = AppSettings.ShowID;

                }
                else
                {
                    BackgroundAudioPlayer.Instance.Pause();
                    AppSettings.SongPlayImage = string.Empty;

                }
            }
        }
            catch (Exception ex)
            {
                
             Exceptions.SaveOrSendExceptions("Exception in LoadDownLoads method In ShowAudio.cs file.", ex);
            }
        }
        public void LoadDownLoads(ShowLinks linkinfo)
        {
            try
            {
            string linktype = "";
            AppSettings.ShowLinkTitle = linkinfo.LinkUrl;
                AppSettings.AudioTitle = linkinfo.Title;
            if (linktype == ".jpg" || linktype == ".png")
            {
                galleryPopup.Show(linkinfo.LinkID.ToString());
            }
            else
            {
                if (linkinfo.Songplay == Constants.PlayImagePath)
                {
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == linkinfo.LinkUrl)
                            {

                                cb.IsIndeterminate = true;
                            }
                        }
                    }
                    if (lbxAudioList.ItemsSource != null)
                    {

                        History objHistory = new History();
                        objHistory.SaveAudioHistory((lbxAudioList.SelectedItem as ShowLinks).ShowID.ToString(), (lbxAudioList.SelectedItem as ShowLinks).Title);
                    }
                    AudioTrack audioTrack = new AudioTrack();
                    audioTrack.BeginEdit();
                    string url = string.Empty;
                    if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        url = ResourceHelper.ProjectName + "/Songs/" + linkinfo.LinkUrl;
                    else
                        url = linkinfo.LinkUrl;
                    audioTrack.Source = new Uri(url, UriKind.RelativeOrAbsolute);
                    audioTrack.Title = linkinfo.Title;
                    audioTrack.EndEdit();
                    BackgroundAudioPlayer.Instance.Track = audioTrack;
                    BackgroundAudioPlayer.Instance.Play();
                    BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                    AppSettings.AudioShowID = AppSettings.ShowID;

                }
                else
                {
                    BackgroundAudioPlayer.Instance.Pause();
                    AppSettings.SongPlayImage = string.Empty;

                }
            }
        }
            catch (Exception ex)
            {
   
               Exceptions.SaveOrSendExceptions("Exception in LoadDownLoads Method In ShowAudio file.", ex);
            }
        }
   
           #endregion

        #region Events
   
        void lbxAudioList_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
            if (PhoneApplicationService.Current.State.Keys.Contains("searchtitle"))
            {
                PageHelper.SetSelectedItemForegroundColor(this.lbxAudioList, AppState.searchtitle);
            }
            else
            {
                PageHelper.SetSelectedItemForegroundColor(this.lbxAudioList, "");
            }

            }
            catch (Exception ex)
            {
           
                Exceptions.SaveOrSendExceptions("Exception in lbxAudioList_Loaded method In ShowAudio.cs file.", ex);
            }
           
        }
        public void lbxAudioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          
            try
            {
            if (lbxAudioList.SelectedIndex == -1)
                return;

            if (ringtoneimageclicked == true)
            {
                lbxAudioList.SelectedIndex = -1;
                return;
            }

            if (Constants.Synthesizer != null)
            {
                Constants.Synthesizer.CancelAll();
            }
            performanceProgressBar.IsIndeterminate = true;
            string showid = (lbxAudioList.SelectedItem as ShowLinks).ShowID.ToString();
                AppSettings.LinkTitle = (lbxAudioList.SelectedItem as ShowLinks).Title.ToString();
                AppSettings.LinkType = (lbxAudioList.SelectedItem as ShowLinks).LinkType.ToString();
            LoadDownLoads(lbxAudioList.SelectedItem as ShowLinks);
            AppSettings.SongID = (lbxAudioList.SelectedItem as ShowLinks).LinkID.ToString();
            AppSettings.AudioImage = (lbxAudioList.SelectedItem as ShowLinks).Songplay;
            Thread AudioThread = new Thread(() =>
            {
                objAudioList = OnlineShow.GetShowLinksByTypeForWp8(showid, LinkType.Audio/*, false*/);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    lbxAudioList.ItemsSource = objAudioList;
                });

            });
            AudioThread.Start();
            lbxAudioList.SelectedIndex = -1;
            performanceProgressBar.IsIndeterminate = false;
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in lbxAudioList_SelectionChanged method In ShowAudio.cs file.", ex);
            }
        }
        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            PlayState playState = BackgroundAudioPlayer.Instance.PlayerState;
            switch (playState)
            {
               
                case PlayState.Paused:
                    IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

                case PlayState.Playing:
                      List<Parameter> Params = new List<Parameter> { new Parameter(AppSettings.LinkType, AppSettings.LinkTitle) };
                    FlurryWP8SDK.Api.LogEvent(AppSettings.Title, Params);
                    IEnumerable<DependencyObject> cboxes1 = PageHelper.GetChildsRecursive(lbxAudioList);

                    foreach (DependencyObject obj in cboxes1.OfType<PerformanceProgressBar>())
                    {
                        Type type = obj.GetType();
                        if (type.Name == "PerformanceProgressBar")
                        {
                            PerformanceProgressBar cb = obj as PerformanceProgressBar;
                            if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                            {

                                cb.IsIndeterminate = false;
                            }
                        }
                    }

                    break;

            }

        }
        private void btnaudioFavSong_Click(object sender, RoutedEventArgs e)
        {
            detailModel.AddToFavorites(lbxAudioList, sender as MenuItem, LinkType.Audio);
        }
        private void btnaudioBrokenSong_Click(object sender, RoutedEventArgs e)
        {
            detailModel.ReportBrokenLink(lbxAudioList, sender as MenuItem);
        }
        private void audiosharelink_Click(object sender, RoutedEventArgs e)
        {
            detailModel.PostAppLinkToSocialNetworks(lbxAudioList, sender as MenuItem, " Listen to Bollywood Song ");
        }
        private void audioratelink_Click(object sender, RoutedEventArgs e)
        {
            detailModel.RateThisLink(lbxAudioList, sender as MenuItem, AppResources.DetailPageName);
        }
        private void ContextMenu_Opened(object sender, RoutedEventArgs e)
        {
           
            try
            {
            ContextMenu mainmenu = sender as ContextMenu;
            foreach (MenuItem contextMenuItem in mainmenu.Items)
            {
                ListBoxItem selectedListBoxItem = this.lbxAudioList.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                if (contextMenuItem.Name == "Pin")
                {
                    if (ShellTileHelper.IsPinned(AppSettings.ShowID + (selectedListBoxItem.Content as ShowLinks).Title))
                    {
                        contextMenuItem.Header = Constants.UnpinFromStartScreen;
                    }
                    else
                    {
                        contextMenuItem.Header = Constants.PinToStartScreen;
                    }
                }
                if (contextMenuItem.Name == "Rating")
                {
                    contextMenuItem.Header = AppResources.AllowRatingLinkContextMenuLabel;
                }
                if (contextMenuItem.Name.Contains("favorites"))
                {
                    int showid1 = Convert.ToInt32(AppSettings.ShowID);
                    int linkid = (selectedListBoxItem.Content as ShowLinks).LinkID;
                    string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                    if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkID == linkid && i.LinkType == linktype).FirstOrDefaultAsync()).Result.IsFavourite == false)
                    {
                        contextMenuItem.Header = "add to favorites";
                    }
                    else
                        contextMenuItem.Header = "remove from favorites";
                }
            }
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            int showid = AppSettings.ShowUniqueID;
            if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
            {

                var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                item.IsEnabled = true;
            }
            else
            {
                var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                item.IsEnabled = false;
            }
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened method In ShowAudio.cs file.", ex);
            }
        }
     
        private void btnpintostart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            string showLinkTitle;
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
            Page p = frame.Content as Page;
                Pivot p1 = (Pivot)(p.FindName("pvtMainDetails"));
                if (p1 != null)
            Constants.topsongnavigation = p1.SelectedIndex.ToString();
            ListBoxItem selectedListBoxItem = this.lbxAudioList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            if (selectedListBoxItem == null)
                return;
            showLinkTitle = (selectedListBoxItem.Content as ShowLinks).Title;
            AppSettings.ShowLinkTitle = AppSettings.ShowID + (selectedListBoxItem.Content as ShowLinks).Title;
            ShellTileHelper.PinVideoLinkToStartScreen(AppSettings.ShowID, selectedListBoxItem.Content as ShowLinks);
        }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in btnpintostart_Click method In ShowAudio.cs file.", ex);
            }
        }
        private void ringtone_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
            ringtoneimageclicked = true;
            Image ringtoneimage = sender as Image; 

            if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
            {

                if (MessageBox.Show("This app needs permision to stop the Background Music.Is it ok to stop currently playing music?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    BackgroundAudioPlayer.Instance.Close();
                    //ListBoxItem selectedListBoxItem = this.lbxAudioList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;



                    AppSettings.Chapterno = ringtoneimage.Tag.ToString().Split(',')[0];
                        if (AppSettings.Chapterno.Contains('\n'))
                            AppSettings.Chapterno = AppSettings.Chapterno.Replace("\n", "");
                    AppSettings.ShowLinkTitle = ringtoneimage.Tag.ToString().Split(',')[1];
                   

                    PageHelper.NavigateToRingTonePage(AppResources.RingTonePageName, AppSettings.ShowLinkTitle, AppSettings.ShowID, AppSettings.Chapterno);
                }

            }
            else
            {
                BackgroundAudioPlayer.Instance.Close();
                //ListBoxItem selectedListBoxItem = this.lbxAudioList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                AppSettings.Chapterno = ringtoneimage.Tag.ToString().Split(',')[0];
                if (AppSettings.Chapterno.Contains('\n'))
                AppSettings.Chapterno = AppSettings.Chapterno.Replace("\n", "");
                AppSettings.ShowLinkTitle = ringtoneimage.Tag.ToString().Split(',')[1];

                PageHelper.NavigateToRingTonePage(AppResources.RingTonePageName, AppSettings.ShowLinkTitle, AppSettings.ShowID, AppSettings.Chapterno);

            }
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in ringtone_MouseLeftButtonDown method In ShowAudio.cs file.", ex);
            }
        }
        private async void del_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
            MenuItem menu = sender as MenuItem;
            ListBoxItem selectedListBoxItem = lbxAudioList.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            int showid = (selectedListBoxItem.Content as ShowLinks).ShowID;
            int linkid = (selectedListBoxItem.Content as ShowLinks).LinkID;
            string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
            var xquery = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(id => id.ShowID == showid && id.LinkID == linkid && id.LinkType == linktype).FirstOrDefaultAsync()).Result;
                if (xquery != null)
            {
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {
                        await Constants.connection.DeleteAsync(xquery);
                     
                }
            }
            GetPageDataInBackground();
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in del_Click_1 method In ShowAudio.cs file.", ex);
            }
        }
        #endregion
    }
}
